package at.fhj.itm10.ticketmaster.beans;

import java.util.Date;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;

import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.entities.Customer;
import at.fhj.itm10.ticketmaster.helper.MD5HashmakerEmail;
import at.fhj.itm10.ticketmaster.services.ServiceFactory;


/**
 * Bean to reset the users password.
 * 
 * @author Wolfgang Gaar
 */
@ManagedBean(name="resetPasswordBean")
@SessionScoped
public class ResetPasswordBean {
	
	private final Logger logger = Logger.getLogger(ResetPasswordBean.class);
	private LoginBean loginBean;
	private String resetKey;
	private String email;
	private boolean resetPossible = false;
	private String newPassword;
	
	private ServiceFactory factory;
	private Customer customer;
	
	private String resetStatus;

	@PostConstruct
	public void init() {
		logger.debug("init()");
		
		FacesContext context = FacesContext.getCurrentInstance();
		loginBean = (LoginBean) context.getApplication()
				.evaluateExpressionGet(context,
						"#{loginBean}", LoginBean.class);
		
		refreshVarsIfNeeded();
		
		this.resetStatus = "";
    	this.factory = new ServiceFactory();
	}

	private void refreshVarsIfNeeded() {
		FacesContext context = FacesContext.getCurrentInstance();
		
		resetKey = (String) context.getApplication()
				.evaluateExpressionGet(context,
						"#{param.resetKey}", String.class);
		
		email = (String) context.getApplication()
				.evaluateExpressionGet(context,
						"#{param.email}", String.class);
	}
	
	public String resetPassword() throws Exception {
		this.customer = factory.getCustomerService().findByEMail(this.email);
		Date dt = new Date();
		String resetKey = MD5HashmakerEmail.generateMD5Code(email+"recoveredon"+dt.getTime());
		if (customer != null) {
			this.factory.getCustomerService().sendRecoveryMail(email, resetKey);
			this.customer.setReset(true);
			this.customer.setResetKey(resetKey);
			this.factory.getCustomerService().updateCustomer(customer);
			return "PasswordReseted";
		}
		else {
			this.setResetStatus("E-Mail Adresse nicht vorhanden!");
			return "PasswordUnableToReset";
		}
	}
	
	public String getResetKey() {
		return resetKey;
	}

	public void setResetKey(String resetKey) {
		this.resetKey = resetKey;
	}
	
	/**
	 * Called when the real reset password form is shown.
	 * @throws DAOException
	 */
	public void showResetPasswordForm() throws DAOException {
		logger.debug("showResetPasswordForm()");

		if (loginBean.isLoggedIn()) {
			logger.debug("showResetPasswordForm() exited at isLoggedIn condition");
			
			resetPossible = false;
			return;
		}

		if (resetKey == null || resetKey.isEmpty() || email == null || email.isEmpty()) {
			logger.debug("showResetPasswordForm() exited at empty condition, resetKey = "
					+ resetKey + ", email = " + email);
			
			resetPossible = false;
			return;
		}

		Customer customer = factory.getCustomerService().findByEMail(email);
		if (customer == null) {
			logger.debug("showResetPasswordForm() exited at customer check condition");
			
			resetPossible = false;
			return;
		}
		
		if (!customer.isReset() || !customer.getResetKey().equals(resetKey)) {
			logger.debug("showResetPasswordForm() exited at non-match data condition, isReset = "
					+ customer.isReset() + ", key = " + customer.getResetKey());
			
			resetPossible = false;
			return;
		}

		resetPossible = true;
	}
	
	/**
	 * Called if the user has entered a new password.
	 * 
	 * @return String
	 */
	public String doSetPassword() {
		logger.debug("doSetPassword()");
		
		try {
			factory.getCustomerService()
					.resetCustomerPasswordByEMail(email, newPassword); //zumtesten
		} catch (Exception e) {
			logger.error(e);	

			return "FormError";
		}
		
		return "Success";
    }

	public boolean isResetPossible() {
		return resetPossible;
	}

	public void setResetPossible(boolean resetPossible) {
		this.resetPossible = resetPossible;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}
	
	public String getResetStatus() {
		return resetStatus;
	}

	public void setResetStatus(String resetStatus) {
		this.resetStatus = resetStatus;
	}

}
